package cbh.tool.mybatis.crud;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;


/**
 * 
 * 提供基础支持的接口。<br>
 * 
 * 挪了，以后想扩展使用再说。
 * 
 * @author cyzhang
 *
 */
public abstract class DbSupport {

    @Autowired
    private SqlSessionFactory factory;

    private SqlSession sqlSession;

    @PostConstruct
    private void init() {
        this.setSqlSessionFactory(this.factory);
    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        if (this.sqlSession != null) {
            this.sqlSession.close();
        }
        this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
    }

    protected SqlSession getSqlSession() {
        checkDaoConfig();
        return this.sqlSession;
    }

    private void checkDaoConfig() {
        Assert.notNull(this.sqlSession,
            "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
    }
}
